import React, { useEffect, useRef, useState } from 'react';
import { ArrowLeft } from '@nutui/icons-react';
import { Uploader, ConfigProvider, NavBar, Toast, Cell, Button,Ellipsis } from '@nutui/nutui-react';
import { useLocation, useNavigate } from 'react-router-dom';
import { http } from '../../utils'
import styles from './SelfMessage.module.css'
import { ArrowRight } from '@nutui/icons-react'
import { useSelector } from 'react-redux';
const SelfMessage = () => {
    const navigate = useNavigate();
    const location = useLocation()
    const [userMessage, setUserMessage] = useState({})
    const createRef = useRef(false)
    useEffect(() => {
        if (!createRef.current) {
            getUserMessage()
            createRef.current = true
        }
    }, [])

    const getUserMessage = async () => {
        let res = await http.get('/main/userMessage')
        if(res.code == 200){
            setUserMessage({...res.data})
        }
    }


    // 上传文件的接口地址
    const uploadUrl = 'http://localhost:3000/main/upload'; // 替换为你的后端接口地址

    // 文件上传前的校验
    const beforeUpload = async (files) => {
        const allowedTypes = ['image/png', 'image/jpeg', 'image/gif']; // 允许的文件类型
        const filteredFiles = Array.from(files).filter((file) =>
            allowedTypes.includes(file.type)
        );

        if (filteredFiles.length === 0) {
            Toast.fail('只允许上传 PNG、JPEG 或 GIF 文件');
            return []; // 返回空数组表示不允许上传
        }

        return filteredFiles;
    };

    // 文件上传成功后的回调
    const onSuccess = (response) => {
        let res = JSON.parse(response.responseText)
        if (res.code == 200) {
            Toast.show({
                content: '上传成功',
                icon: 'success',
            });
            onPutUserHead(res.data.filePath)
            console.log('文件路径:', res.data.filePath);
        } else {
            Toast.show({
                content: '上传失败',
                icon: 'fail',
            });
        }
    };

    // 文件上传失败后的回调
    const onFailure = () => {
        Toast.show({
            content: '上传失败，请重试',
            icon: 'fail',
        });
    };

    const onPutUserHead = async (path) => {
        let res = await http.post('/main/putUserHead', { head: path })
        if (res.code == 200) {
            setUserMessage({ ...userMessage, head: path })
        }
    }

    // 自定义主题
    const darkTheme = {
        nutuiNavbarBackground: '#f7f7f7',
        nutuiNavbarHeight: '0.5rem',
    };


    return (
        <div style={{backgroundColor: '#f7f7f7',height:"100vh"}}>
            <ConfigProvider theme={darkTheme}>
                <div style={{paddingTop:"0.15rem"}}>
                    <NavBar
                        back={<ArrowLeft />}
                        onBackClick={() => navigate(-1)}
                    >
                        个人信息
                    </NavBar>
                </div>
                <div className={styles.self_img_box}>
                    <img className={styles.self_img_head} src={`http://localhost:3000${userMessage.head}`} alt="" />
                    <Uploader
                        beforeUpload={beforeUpload}
                        url={uploadUrl}
                        onSuccess={onSuccess}
                        onFailure={onFailure}
                        style={{
                            marginInlineEnd: '10px',
                            marginBottom: '10px',
                        }}
                    >
                        <span style={{ fontSize: '0.16rem', color: '#737373' }}>点击修改图像</span>
                    </Uploader>
                </div>
                <div className={styles.self_fun_box}>
                    <Cell.Group>
                        <Cell
                            className="nutui-cell-clickable"
                            title="用户名"
                            align="center"
                            extra={<span style={{fontSize:'0.18rem'}}>{userMessage.user}<ArrowRight /></span>}
                            onClick={()=>{
                                navigate('/outlet/putUser',{state:{...userMessage}})
                            }}
                        />
                        <Cell
                            className="nutui-cell-clickable"
                            title="UID"
                            extra={<Ellipsis content={userMessage._id} direction="end" rows={1}/>}
                            align="center"

                        />
                    </Cell.Group>
                </div>
            </ConfigProvider>
        </div>
    );
};

export default SelfMessage;